//
//  NRWCarTabbarView.m
//  New_Runway
//
//  Created by mack on 2018/1/22.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarTabbarView.h"
#import "UIView+DDAddition.h"

#define kscale 1.4

typedef enum : NSUInteger {
    
    tabbarAnimationStype_one,
    tabbarAnimationStype_two,
    
} tabbarAnimationStype;
@implementation NRWCarTabbarView
{
    UIImageView *_showImageView;
    UILabel *_showLabel;
    tabbarAnimationStype _tabbarAnimationStype;
    UIImage *_normalImage;
    UIImage *_highlightedImage;
    
}
- (instancetype)initWithFrame:(CGRect)frame Image:(UIImage *)image highlightedImge:(UIImage *)himage Title:(NSString *)title{
    self = [super initWithFrame:frame];
    if (self) {
        _isSelect = NO;
        _highlightedImage = himage;
        _normalImage = image;
        
        _showImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 30, 25)];
        _showImageView.centerX = frame.size.width / 2;
        _showImageView.backgroundColor = [UIColor clearColor];
        [_showImageView setContentMode:UIViewContentModeScaleAspectFit];
        [_showImageView setImage:image];
        [self addSubview:_showImageView];
        
        
        
        _showLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, frame.size.height - 17, frame.size.width, 15)];
        [_showLabel setTextAlignment:NSTextAlignmentCenter];
        _showLabel.backgroundColor = [UIColor clearColor];
        [_showLabel setFont:[UIFont systemFontOfSize:10]];
        _showLabel.textColor = MAIN_TAB_NORMAL();
        //根据图片获取主颜色 有偏差
        _showLabel.text = title;
        [self addSubview:_showLabel];
        
        
        _redPoint = [[UILabel alloc] init];
        _redPoint.frame = CGRectMake(frame.size.width - 35, 5, 10, 10);
        _redPoint.layer.masksToBounds = YES;
        _redPoint.layer.cornerRadius = 5;
        _redPoint.backgroundColor = [UIColor redColor];
        _redPoint.hidden = YES;
        [self addSubview:_redPoint];
        
        UITapGestureRecognizer *_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
        [self addGestureRecognizer:_tap];
        self.userInteractionEnabled = YES;
        
        _tabbarAnimationStype = tabbarAnimationStype_one;
        
    }
    
    
    return self;
}

-(void)tapGestureRecognizer{
    
    
    
    if (_selectFootTabbarBtn) {
        _selectFootTabbarBtn((int)self.tag);
    }
    
    switch (_tabbarAnimationStype) {
        case tabbarAnimationStype_one:
            
            [self tabbarAnimationSelect_one];
            
            break;
            
        case tabbarAnimationStype_two:
            
            [self tabbarAnimationSelect_two];
            
            break;
            
        default:
            break;
    }
}


-(void)tabbarAnimationSelect_one{
    
    if (_isSelect) {
        return;
    }
    
    _isSelect = YES;
    
    [_showImageView.layer removeAllAnimations];
    _showImageView.image = _highlightedImage;
    [UIView animateWithDuration:.2 animations:^{
//        _showLabel.alpha = 0;
        _showLabel.textColor = MAIN_NAV_COLOR();

//        _showImageView.centerY = self.height / 2;
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:.7 delay:0 usingSpringWithDamping:.6 initialSpringVelocity:.8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
//            _showImageView.transform = CGAffineTransformMakeScale(kscale, kscale);
            
        } completion:^(BOOL finished) {
            //            _showImageView.image = _highlightedImage;
            if (_isSelect) {
                if (_showLabel.alpha != 0 || _showImageView.centerY != self.height / 2 || !CGAffineTransformEqualToTransform(_showImageView.transform , CGAffineTransformMakeScale(kscale, kscale))) {
                    [UIView animateWithDuration:.2 animations:^{
//                        _showImageView.transform = CGAffineTransformMakeScale(kscale, kscale);
//                        _showLabel.alpha = 0;
                        _showLabel.textColor = MAIN_NAV_COLOR();
//                        _showImageView.centerY = self.height / 2;
                    }];
                }
            }
        }];
    }];
}

-(void)tabbatAnimationUnselected_one{
    
    if (!_isSelect) {
        return;
    }
    
    _isSelect = NO;
    
    [_showImageView.layer removeAllAnimations];
    _showImageView.image = _normalImage;
    [UIView animateWithDuration:.2 animations:^{
        
//        _showImageView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:.2 animations:^{
//            _showLabel.alpha = 1;
            _showLabel.textColor = MAIN_TAB_NORMAL();

//            _showImageView.top = 3;
        } completion:^(BOOL finished) {
            
            if (!_isSelect) {
                if (_showLabel.alpha != 1 || _showImageView.top != 3 || !CGAffineTransformEqualToTransform(_showImageView.transform , CGAffineTransformMakeScale(1, 1)) ) {
                    [UIView animateWithDuration:.2 animations:^{
//                        _showImageView.transform = CGAffineTransformMakeScale(1, 1);
//                        _showLabel.alpha = 1;
                        _showLabel.textColor = MAIN_TAB_NORMAL();

//                        _showImageView.top = 3;
                    }];
                }
            }
            
        }];
    }];
}


- (instancetype)initWithFrame:(CGRect)frame Image:(UIImage *)image highlightedImge:(UIImage *)himage{
    self = [super initWithFrame:frame];
    if (self) {
        _isSelect = NO;
        
        _normalImage = image;
        _highlightedImage = himage;
        
        _showImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 33, 49)];
        _showImageView.centerX = frame.size.width / 2;
        _showImageView.backgroundColor = [UIColor clearColor];
        [_showImageView setContentMode:UIViewContentModeScaleAspectFit];
        [_showImageView setImage:_normalImage];
        [self addSubview:_showImageView];
        
        UITapGestureRecognizer *_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
        [self addGestureRecognizer:_tap];
        self.userInteractionEnabled = YES;
        
        _tabbarAnimationStype = tabbarAnimationStype_two;
    }
    
    return self;
}

-(void)tabbarAnimationSelect_two{
    
    
    [UIView animateWithDuration:0.5 delay:0.0 usingSpringWithDamping:0.6 initialSpringVelocity:0.6 options:UIViewAnimationOptionCurveLinear animations:^{
        CALayer *viewLayer = _showImageView.layer;
        // 获取当前View的位置
        CGPoint position = viewLayer.position;
        // 移动的两个终点位置
        CGPoint x = CGPointMake(position.x + 2, position.y);
        CGPoint y = CGPointMake(position.x - 2, position.y);
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
        [animation setFromValue:[NSValue valueWithCGPoint:x]];
        [animation setToValue:[NSValue valueWithCGPoint:y]];
        [animation setAutoreverses:YES];
        [animation setRepeatCount:0];
        [viewLayer addAnimation:animation forKey:nil];
        
        
        //        CATransition *transition=[[CATransition alloc]init];
        //        transition.type=@"cube";
        //        transition.duration=0.5f;
        //        // _showImageView.image=[self getImage:isNext];
        //        [_showImageView.layer addAnimation:transition forKey:@"KCTransitionAnimation"];
        
    } completion:^(BOOL finished) {
        
        [_showImageView setImage:_highlightedImage];
        
    }];
    
}

-(void)tabbarAnimationUnselected_two{
    [_showImageView setImage:_normalImage];
}

- (void)setBtnSelect:(BOOL)select{
    if (select) {
        [self tapGestureRecognizer];
    }else{
        switch (_tabbarAnimationStype) {
            case tabbarAnimationStype_one:
                [self tabbatAnimationUnselected_one];
                break;
                
            case tabbarAnimationStype_two:
                
                [self tabbarAnimationUnselected_two];
                
                break;
                
            default:
                break;
        }
    }
    
}
-(UIColor*)mostColor:(UIImage*)image{
    
    //#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
    //#else
    //    int bitmapInfo = kCGImageAlphaPremultipliedLast;
    //#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width/2, image.size.height/2);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}

@end
